package com.openluat.LuatTestServer.utils;

import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class Utils {
    public static String getFileMD5(File f) {
        BigInteger bi = null;
        try {
            byte[] buffer = new byte[8192];
            int len;
            MessageDigest md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(f);
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            fis.close();
            byte[] b = md.digest();
            bi = new BigInteger(1, b);
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
        String res = bi.toString(16).toUpperCase();
        for (int i = 0; i < 32 - res.length(); i++) {
            res = "0" + res;
        }
        return res;
    }

    public static String getFileStreamMD5(InputStream f) {
        BigInteger bi = null;
        try {
            byte[] buffer = new byte[8192];
            int len;
            MessageDigest md = MessageDigest.getInstance("MD5");
            while ((len = f.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            f.close();
            byte[] b = md.digest();
            bi = new BigInteger(1, b);
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
        String res = bi.toString(16).toUpperCase();
        for (int i = 0; i < 32 - res.length(); i++) {
            res = "0" + res;
        }
        return res;
    }

    public static String getStringMD5(String s) {
        BigInteger bi = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(s.getBytes());
            byte[] b = md.digest();
            bi = new BigInteger(1, b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String res = bi.toString(16).toUpperCase();
        for (int i = 0; i < 32 - res.length(); i++) {
            res = "0" + res;
        }
        return res;
    }
}
